using Prism.Commands;
using Prism.Mvvm;
using S7.Net;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Threading;
using MoniterPLC;

namespace MoniterPLC.ViewModel
{
    /// <summary>
    /// 主窗口视图模型，负责处理UI交互和数据绑定
    /// </summary>
    public class MainViewModel : BindableBase
    {
        private readonly PLCService _plcService;
        private string _ipAddress = "192.168.0.1";
        private string _rack = "0";
        private string _slot = "1";
        private bool _isConnected;
        private string _connectionStatus = "未连接";
        private ObservableCollection<StationModel> _stations;

        /// <summary>
        /// 工位列表，用于绑定到UI显示
        /// </summary>
        public ObservableCollection<StationModel> Stations
        {
            get { return _stations; }
            set { SetProperty(ref _stations, value); }
        }

        /// <summary>
        /// PLC的IP地址
        /// </summary>
        public string IpAddress
        {
            get { return _ipAddress; }
            set { SetProperty(ref _ipAddress, value); }
        }

        /// <summary>
        /// PLC的机架号
        /// </summary>
        public string Rack
        {
            get { return _rack; }
            set { SetProperty(ref _rack, value); }
        }

        /// <summary>
        /// PLC的槽号
        /// </summary>
        public string Slot
        {
            get { return _slot; }
            set { SetProperty(ref _slot, value); }
        }

        /// <summary>
        /// 是否已连接到PLC
        /// </summary>
        public bool IsConnected
        {
            get { return _isConnected; }
            set { SetProperty(ref _isConnected, value); }
        }

        /// <summary>
        /// 连接状态文本
        /// </summary>
        public string ConnectionStatus
        {
            get { return _connectionStatus; }
            set { SetProperty(ref _connectionStatus, value); }
        }

        /// <summary>
        /// 连接PLC命令
        /// </summary>
        public DelegateCommand ConnectCommand { get; private set; }

        /// <summary>
        /// 断开连接命令
        /// </summary>
        public DelegateCommand DisconnectCommand { get; private set; }

        /// <summary>
        /// 进入模拟模式命令
        /// </summary>
        public DelegateCommand SimulationCommand { get; private set; }

        /// <summary>
        /// 初始化主窗口视图模型
        /// </summary>
        public MainViewModel()
        {
            _plcService = new PLCService();
            _plcService.ConnectionStatusChanged += OnConnectionStatusChanged;
            _plcService.InitializeStations();
            _stations = _plcService.Stations;

            // 初始化命令
            ConnectCommand = new DelegateCommand(Connect, CanConnect);
            DisconnectCommand = new DelegateCommand(Disconnect, CanDisconnect);
            SimulationCommand = new DelegateCommand(Simulate, CanSimulate);
        }

        /// <summary>
        /// 检查是否可以连接PLC
        /// </summary>
        /// <returns>如果未连接则返回true</returns>
        private bool CanConnect()
        {
            return !IsConnected;
        }

        /// <summary>
        /// 检查是否可以断开连接
        /// </summary>
        /// <returns>如果已连接则返回true</returns>
        private bool CanDisconnect()
        {
            return IsConnected;
        }

        /// <summary>
        /// 检查是否可以进入模拟模式
        /// </summary>
        /// <returns>如果未连接则返回true</returns>
        private bool CanSimulate()
        {
            return !IsConnected;
        }

        /// <summary>
        /// 连接PLC
        /// </summary>
        private void Connect()
        {
            if (string.IsNullOrEmpty(IpAddress))
            {
                MessageBox.Show("请输入PLC IP地址");
                return;
            }

            try
            {
                int.TryParse(Rack, out int rack);
                int.TryParse(Slot, out int slot);
                
                bool connected = _plcService.ConnectAsync(IpAddress, rack, slot, CpuType.S71200).Result;
                
                if (!connected)
                {
                    MessageBox.Show("连接PLC失败，请检查IP地址和网络连接");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"连接出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 断开与PLC的连接
        /// </summary>
        private void Disconnect()
        {
            try
            {
                _plcService.DisconnectAsync().Wait();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"断开连接出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 进入模拟模式
        /// </summary>
        private void Simulate()
        {
            try
            {
                _plcService.EnterSimulationMode();
                MessageBox.Show("已进入模拟模式");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"进入模拟模式出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 连接状态改变事件处理程序
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="isConnected">是否已连接</param>
        private void OnConnectionStatusChanged(object? sender, bool isConnected)
        {
            // 使用UI线程更新界面
            Application.Current.Dispatcher.Invoke(() =>
            {
                IsConnected = isConnected;
                
                // 更新连接状态文本
                if (_plcService.IsSimulationMode)
                {
                    ConnectionStatus = "模拟模式";
                }
                else
                {
                    ConnectionStatus = isConnected ? "已连接" : "未连接";
                }
                
                // 更新命令的可执行状态
                ConnectCommand.RaiseCanExecuteChanged();
                DisconnectCommand.RaiseCanExecuteChanged();
                SimulationCommand.RaiseCanExecuteChanged();
            });
        }
    }
}